<template>
    <div class="home-container">

        <!-- 5G/设备状态连接图示 -->
        <div class="network-status-container flex-center" v-if="false">
            <div class="network-left">
                <img src="@/assets/images/network@2x.png" alt="网络" draggable="false" />
                <div class="network-text">{{ netWork }} ONLINE</div>
            </div>
            <!-- 5G/设备状态连接图示 这里实现上中下的布局-->
            <div class="green-line-up-box">
                <div class="green-line-up"> <img src="@/assets/images/wifi.png" alt="wifi" draggable="false" />2.4G</div>
                <div class="green-line"></div>
                <div class="green-line-below"><img src="@/assets/images/wifi.png" alt="wifi" draggable="false" />5G</div>
            </div>

            <div class="network-left">
                <img src="@/assets/images/img_productDrawing@2x.png" alt="" draggable="false" />
            </div>
            <!-- venard 上下行速率 -->
             <div class="green-line-up-box">
                <div class="green-line-up"><img src="@/assets/images/upload.png" alt="upload" draggable="false" />{{uplink_rate}}</div>
                <div class="green-line"></div>
                <div class="green-line-below"><img src="@/assets/images/download.png" alt="download" draggable="false" />{{downlink_rate}}</div>
            </div>


            <div class="mobile-device">
                <img src="@/assets/images/device@2x.png" alt="设备" draggable="false" />
                <div class="network-text">{{ $t('dataBoard.deviceTitle') }}</div>  
            </div>
        </div>

        <!-- WiFi信息卡片 -->
        <div class="wifi-info-container flex-center">
            <!-- 2.4GHz WiFi信息 -->
            <div class="wifi-card">
                <div class="wifi-header flex-center">
                    <div class="wifi-icon">
                     <img src="@/assets/images/wifi2.png" draggable="false" />
                    </div>
                    <div class="wifi-type">2.4GHz WiFi</div>
                    <div class="details-button">
                        <el-button type="primary" size="small" round @click="goToWifiSettings('2.4G')">Details</el-button>
                    </div>
                </div>
                <div class="wifi-content">
                    <div class="wifi-row">
                        <div class="wifi-label">WiFi Name</div>
                        <div class="wifi-value">{{ wifiInfo['2.4G'].wifiName}}</div> 
                    </div>
                    <div class="wifi-row">
                        <div class="wifi-label">Password</div>
                        <div class="wifi-value password-field">
                            <span v-if="wifiInfo['2.4G'].viewPwd" >{{wifiInfo['2.4G'].wifiPwd}}</span>
                            <span v-if="!wifiInfo['2.4G'].viewPwd" >{{'••••••••'}}</span>
                            <span class="password-toggle">
                                <i class="el-icon-view" :class="{ 'viewed': !wifiInfo['2.4G'].viewPwd }" @click="viewWiFiPwd('2.4G')" draggable="false"></i>
                                <i class="el-icon-copy-document" :class="{ 'copied': !wifiInfo['2.4G'].copy }" @click="copyWifiPwd('2.4G')"></i>
                            </span>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- 5GHz WiFi信息 -->
            <div class="wifi-card">
                <div class="wifi-header flex-center">
                    <div class="wifi-icon">
                        <img src="@/assets/images/wifi2.png" draggable="false" />
                    </div>
                    <div class="wifi-type">5GHz WiFi</div>
                    <div class="details-button">
                        <el-button type="primary" size="small" round @click="goToWifiSettings('5G')">Details</el-button>
                    </div>
                </div>
                <div class="wifi-content">
                    <div class="wifi-row">
                        <div class="wifi-label">WiFi Name</div>
                        <div class="wifi-value">{{ wifiInfo['5G'].wifiName}}</div>
                    </div>
                    <div class="wifi-row">
                        <div class="wifi-label">Password</div>
                        <div class="wifi-value password-field">
                            <span v-if="wifiInfo['5G'].viewPwd" >{{wifiInfo['5G'].wifiPwd}}</span>
                            <span v-if="!wifiInfo['5G'].viewPwd" >{{'••••••••'}}</span>
                            <span class="password-toggle">
                                <i class="el-icon-view" :class="{ 'viewed': !wifiInfo['5G'].viewPwd }" @click="viewWiFiPwd('5G')" draggable="false"></i>
                                <i class="el-icon-copy-document" :class="{ 'copied': !wifiInfo['5G'].copy }" @click="copyWifiPwd('5G')"></i>
                            </span>
                        </div>
                    </div>
                </div>
            </div>
        </div>

    </div>

</template>

<script>
import { LOCAL_KEY } from '@/constant/dict';


import useRoam from '@/hooks/useRoam';
import useDataLimit from '@/hooks/useDataLimit';

import {  signalIconObj, wifiIcon, passwordIcon,  } from './components/dataBoard.data';

//venard import
import {getCellularDataSetting } from '@/api/cellular';
import {getInfoWireless, } from '@/api/wireless';
import { getInternetInfo } from '@/api/mobile';


export default {
    components: { },
    mixins: [useRoam, useDataLimit],
    
    data() {
        return {
            // 是否显示 SIM 卡状态
            showSimStatus: true,

            // SIM 卡状态
            simStatus: '',
            simStatus_026: '',

            // SIM 卡是否在线
            simOnline: false,

            // SIM 卡图标路径
            simCardIconPath: '',

            // 是否显示网速
            showSpeed: false,

            // 请求数据定时器
            timer: null,

            // 请求网速定时器
            speedTimer: null,

            // 是否在线
            isOnLine: true,

            // 是否 4.5G
            is4Drop5G: false,

            // 网络状态
            netWork: '--',

            // 跳转链接地址
            jumpUrlStr: '',

            // 信号图标
            signalIconPath: signalIconObj[0],

            // 连接设备数量
            linkDeviceNumber: 0,

            // 流量使用情况
            monthDay: '',
            monthDayUsed: '',
            sessionDayUsed: '',
            onlineTime: '',
            monthClearDay: 1,
            monthTX: '',
            monthRX: '',
            sessionTX: '',
            sessionRX: '',

            // 是否单频 WIFI 或 双频合一显示单 WIFI
            singleWiFi: false,

            // WIFI 信息
            wifiInfo: {
                '2.4G': {
                    wifiIcon: wifiIcon['off'],
                    wifiType: '2.4GHz Wi-Fi',
                    wifiName: ' ',
                    wifiPwd: '',
                    eyeIcon: passwordIcon['hide'],
                    viewPwd: false,
                    copy: true,
                    securityType: '',
                    wifiNameID: 'wifiName_2_4',
                    wifiPwdID: 'wifiPwd_2_4',
                    viewPwdID: 'passwordIcon_2_4',
                    copyBtnID: 'copyBtn_2_4',
                    detailsBtnID: 'detailsBtn_2_4',
                    isShow: true,
                    qrcodeData: '',
                    channel: '',
                },
                '5G': {
                    wifiIcon: wifiIcon['off'],
                    wifiType: '5GHz Wi-Fi',
                    wifiName: '',
                    wifiPwd: '',
                    eyeIcon: passwordIcon['hide'],
                    viewPwd: false,
                    copy: true,
                    securityType: '',
                    wifiNameID: 'wifiName_5',
                    wifiPwdID: 'wifiPwd_5',
                    viewPwdID: 'passwordIcon_5',
                    copyBtnID: 'copyBtn_5',
                    detailsBtnID: 'detailsBtn_5',
                    isShow: true,
                    qrcodeData: '',
                    channel: '',
                },
                '6G': {
                    wifiIcon: wifiIcon['off'],
                    wifiType: '6GHz Wi-Fi',
                    wifiName: '',
                    eyeIcon: passwordIcon['hide'],
                    viewPwd: false,
                    copy: true,
                    securityType: '',
                    wifiNameID: 'wifiName_6',
                    wifiPwdID: 'wifiPwd_6',
                    viewPwdID: 'passwordIcon_6',
                    copyBtnID: 'copyBtn_6',
                    detailsBtnID: 'detailsBtn_6',
                    isShow: false,
                    qrcodeData: '',
                    channel: '',
                }
            },

            // WiFi 密码
            wifiPwd: {
                '2.4G': '',
                '5G': '',
                '6G': ''
            },


            // 项目所支持的WIFI模式
            wifiType: JSON.parse(localStorage.getItem(LOCAL_KEY.WIFI_TYPE)) || [true, true, false],

            wanOnline: false,

            //venard.zhou流量信息
            cellular_enable:true,
            limit_mode:"",
            data_usage:0,
            data_allowance:0,
            uplink_rate: 0,
            downlink_rate:0,

            //闲时流量设置
            start_time:0,
            end_time:0,
        };
    },

    methods: {
      

        // 查看 WIFI 密码
        viewWiFiPwd(type) {
            const info = this.wifiInfo[type];
            const isPwdHidden = !info.viewPwd;

            info.eyeIcon = isPwdHidden ? passwordIcon['open'] : passwordIcon['hide'];
            // info.wifiPwd = isPwdHidden ? this.wifiPwd[type] : '•••••••••';
            info.viewPwd = !info.viewPwd;
        },

      
        // 复制 WIFI 密码
        copyWifiPwd(type) {
            this.wifiInfo[type].copy = false;

            // 创建临时元素，将选中的文本放进临时元素中
            let tmpEle = document.createElement('textarea');
            if (this.wifiInfo[type].securityType !== 'none') {
               tmpEle.value += this.wifiInfo[type].wifiPwd;
            }

            //将临时元素添加到页面并选择其中的文本
            document.body.appendChild(tmpEle);
            tmpEle.select();

            //复制选中的文本到剪切板中
            document.execCommand('copy');

            this.$message({
                message: this.$t('dataBoard.copySuccessTitle'),
                type: 'success',
                duration: 1500
            });

            //移除临时元素
            document.body.removeChild(tmpEle);

            setTimeout(() => {
                this.wifiInfo[type].copy = true;
            }, 1500);
        },

        // 获取 WIFI 信息地址
        wifiDetailsUrl() {
            return '/netWork/wifiSettings';
        },

        // 跳转WIFI详情
        wifiDetails(type) {
            this.jumpUrl(this.wifiDetailsUrl(), { wifiModeType: type });
        },


        // 跳转链接
        jumpUrl(_type, query) {
            this.$router.replace({
                path: _type,
                query
            });
        },

      

        // 请求数据统一方法
        async getData() {
          await this.wifiInfoData();
          await this.cellularData();
          await this.getOnlineInfo();
        },

        // 需要轮询获取的数据
        async pollingData() {
            await this.getData();

            this.timer = setInterval(async () => {
                await this.getData();
            }, 5000);
        },
        // venard methods

        goToWifiSettings(type){
            this.$router.push({
                path: '/netWork/wifiSettings',
                query: { wifiModeType: type }
            });  
        },

        // 
        async cellularData(){
            try {
                console.log("开始获取流量信息.....");
                const rawData = await getCellularDataSetting();
                
                if (!rawData) {
                throw new Error("接口返回空数据");
                }

                const { enable, limit_mode, data_usage , data_allowance , uplink_rate, downlink_rate} = rawData;
                console.log("uplink",uplink_rate)
                this.cellular_enable = enable;
                this.limit_mode = limit_mode;
                this.data_usage = data_usage;
                this.data_allowance = data_allowance;
                this.uplink_rate = uplink_rate ;  
                this.downlink_rate = downlink_rate ;

            } catch (err) {
                this.$message.error("获取流量信息失败。");
            }
        },
         // 获取无线信息
        async wifiInfoData(){
           
            try {
                console.log("开始获取无线信息.....");
                const info = await getInfoWireless(24);  
                this.wifiInfo['2.4G'].isShow = info.enable; 
                this.wifiInfo['2.4G'].wifiName = info.ssid; 
                this.wifiInfo['2.4G'].wifiPwd = info.key; 
                this.wifiInfo['2.4G'].securityType = info.encryption; 
                this.wifiInfo['2.4G'].channel = info.channel; 

            } catch (err) {
                console.log("获取无线信息失败。");
            }

            try{
                const info = await getInfoWireless(5); 
                this.wifiInfo['5G'].isShow = info.enable; 
                this.wifiInfo['5G'].wifiName = info.ssid; 
                console.log("wifiName5G:",info.ssid);
                this.wifiInfo['5G'].wifiPwd = info.key; 
                this.wifiInfo['5G'].securityType = info.encryption; 
                this.wifiInfo['5G'].channel = info.channel; 
                console.log("wifiInfo5G",info.key);
            } catch (err) {
                console.log("获取在线信息失败。");
            }

            this.wanOnline = this.wifiInfo['2.4G'].isShow ||  this.wifiInfo['5G'].isShow;
        },

        //获取在线信息
        async getOnlineInfo(){
            console.log("getOnlineInfo----")
            try { 
            const res = await getInternetInfo(); 
            if (!res) {
                console.log("test1:")
            throw new Error("接口返回空数据");
            }
            let usim = res.sim_status;
            console.log("getOnlineInfo:",usim)
            if (usim == '' || usim == '无线装置已关闭' || usim == '不在服务区' || usim == '已断开连接'|| usim == '未知') {
                this.simStatus = 'No SIM';
            } else if (usim == '已连接' || usim == '正在连接'|| usim == '服务中'||usim == 'Connected' || usim == 'Connecting'|| usim == 'In Service') {
                this.simStatus = 'service';
                let generation;
                console.log("test2:")
                switch (res.network_search.network_type) {
                    case "28":
                    generation= '5G';    // 5G网络
                    break;
                    case "9":
                    generation = '4G';    // 4G网络
                    break;
                    case "0":
                    generation = '3G';    
                    break;
                    case "1":
                    generation = '2G';   
                    break;
                    case "5G":
                    generation= '5G';    // 5G网络
                    break;
                    case "4G":
                    generation = '4G';    // 4G网络
                    break;
                    case "3G":
                    generation = '3G';    
                    break;
                    case "2G":
                    generation = '2G';   
                    break;
                    default:
                    generation = '';  
                }
                console.log("generation:",generation)
                this.netWork=generation;

            } else {
                this.simStatus = 'SIM ready';
            }
            console.log("wanOnline:",this.wanOnline)
            if(this.wanOnline){
               this.netWork = "wifi"
            }
              
            } catch (err) {
                console.log("获取在线信息失败",err)
                this.$message.error("获取在线信息失败。");
            }
        }

    },

    created() {
        this.wifiInfoData();
        this.getOnlineInfo();
        this.pollingData();
    },

    beforeDestroy() {
        clearInterval(this.timer);
        clearInterval(this.speedTimer);
    },

    computed: {
        isHideRateInfo() {
            return false;
        }
    },

    watch: {

        // 监听是否显示单 WIFI
        singleWiFi: {
            handler(nVal) {
                this.wifiInfo['5G'].isShow = !nVal;
            },
            immediate: true
        },

        '$store.state.firmware.isRoamStatus': {
            handler(nVal) {
                this.isRoam = nVal;
            },
            immediate: true
        }
    }
};
</script>
<style lang="less" scoped>
@import '@/assets/css/theme_blue/databoard.less';

.el-icon-view.viewed {
  position: relative;
}
.el-icon-view.viewed::after {
  content: "";
  position: absolute;
  top: 50%;
  left: 50%;
  width: 100%;
  height: 2px;
  background: currentColor; /* 使用当前颜色 */
  transform: translate(-50%, -50%) rotate(45deg);
  transform-origin: center;
}

.el-icon-copy-document {
  transition: all 0.3s ease;
}

.el-icon-copy-document.copied {
  color: black;
  font-weight: bold;
  transform: scale(1.1);
}
</style>
